package com.hzx.ssm.service.impl;

import com.hzx.ssm.dao.UserDao;
import com.hzx.ssm.entity.Admin;
import com.hzx.ssm.entity.ResBean;
import com.hzx.ssm.entity.User;
import com.hzx.ssm.service.UserService;
import com.hzx.ssm.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public ResBean registerUser(String username, String password) {
        int existName = userDao.existName(username);
        if (existName > 0) {
            return ResBean.error(401, "用户名已经存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAvailable(1);
        user.setFace("default");
        user.setUser_id(UUID.randomUUID().toString());
        user.setRegistration(new Date());
//注册用户
        userDao.registerUser(user);

        user.setPassword("*******");
        return ResBean.sucess(200, "注册成功", user);
    }

    @Override
    public ResBean login(String username, String password) {

        User user = userDao.findUser(username, password);
        if (user != null && user.getAvailable() == 0) {
            return ResBean.error(400, "账号不可用");
        }
        if (user != null) {
            // 生成token
            String token = JWTUtil.generateToken(user.getUsername(), "Kuroko-Security-Basic", user.getUser_id());
            // 向浏览器返回token，客户端收到此token后存入cookie中，或者h5的本地存储
            HashMap<String, Object> data = new HashMap<>();
            user.setPassword("*******");
            //返回token和用户
            data.put("token", token);
            data.put("user", user);
            return ResBean.sucess(200, "登录成功", data);


        }

        return ResBean.error(401, "账号或密码错误");
    }

    @Override
    public ResBean getUser(String username, String user_id) {
        User user = userDao.getUser(username, user_id);
        user.setPassword("******");
        if (user != null)
            return ResBean.sucess(200, "查找成功", user);
        else
            return ResBean.error(401, "查不到该用户");
    }

    @Override
    public ResBean getAllUser() {
        List<User> users = userDao.getAllUser();
        Iterator<User> iterator = users.iterator();
        while (iterator.hasNext()){
            iterator.next().setPassword("******");
        }
        return ResBean.sucess(200,"查找成功",users);
    }

    @Override
    public ResBean updatePassword(String user_id, String password) {
        userDao.updatePassword(user_id,password);
        return ResBean.sucess(200,"修改密码成功");
    }

    @Override
    public ResBean updateSelfMessage(User user) {
        userDao.updateSelfMessage(user);
        return ResBean.sucess(200,"修改个人信息成功");
    }
}
